import { defineComponent, ref, nextTick } from "vue";
import styles from "./Popup.module.less";
import { CloseOutlined } from "@ant-design/icons-vue";
import _ from "lodash";
export default defineComponent({
  props: {
    //点击浮层可否关闭
    floatingClose: {
      type: Boolean,
      default: true,
    },
    // 弹窗宽度
    width: {
      type: String,
      default: '60%',
    },
    // 弹窗标题
    title: {
      type: String,
      default: '',
    },
    // 弹窗初始状态
    oriState: {
      type: Object,
    },
  },
  emits: ([
    'beforeClose', //弹窗即将关闭时
    'closed', //弹窗关闭后
  ]),
  setup(props, { expose, emit, slots }) {
    // 浮层打开状态
    const floatOpen = ref(false);
    // 卡片打开
    const cardShow = ref(false);

    let _oriState = _.cloneDeep(props.oriState);

    // 浮层
    const PopupScreen = () => (
      <div class={[styles.PopupScreen, floatOpen.value || styles.floatClose]} onClick={() => { props.floatingClose && close() }}>
        <div class={[styles.popupCard, cardShow.value || styles.close]} style={{ '--popup-width': props.width }} onClick={(e) => { e.stopPropagation() }}>
          {
            props.title && (
              <div class={styles.header}>
                <span>{props.title}</span>
                <CloseOutlined class={styles.closeIcon} onClick={() => { close() }} />
              </div>
            )
          }
          <div class={styles.container}>
            {slots.default?.()}
          </div>
          {
            slots.footer && (
              <div class={styles.footer}>
                {slots.footer?.()}
              </div>
            )
          }
        </div>
      </div >
    )
    // 打开弹窗
    const open = () => {
      floatOpen.value = true;
      cardShow.value = true;
    }
    // 关闭弹窗
    const close = () => {
      emit('beforeClose');
      nextTick(() => {
        cardShow.value = false;
        floatOpen.value = false;
        Object.entries(_oriState).forEach(item => {
          props.oriState && (props.oriState[item[0]] = _.cloneDeep(item[1]))
        })
        emit('closed');
      })
    }
    expose({
      open,
      close,
    })
    return () => (
      <>
        {
          <PopupScreen />
        }
      </>
    )
  }
})